package org.patterns.creational.simplefactory;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.net.URL;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

public class XMLUtil {
    //该方法用于从XML配置文件中提取图表类型，并返回类型名
    public static String getChartType() {
        try {
            // 获取文件的URL
            URL url = XMLUtil.class.getResource("config.xml");
            String filePath = url.getFile();
            System.out.println("文件URL: " + URLDecoder.decode(filePath, StandardCharsets.UTF_8));
            //创建文档对象
            DocumentBuilderFactory dFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = dFactory.newDocumentBuilder();
            Document doc;
            doc = builder.parse(filePath);
            //doc = builder.parse(new File("src/main/resources/org/patterns/creational/simplefactory/config.xml"));

            //获取包含图表类型的文本结点
            NodeList nodes = doc.getElementsByTagName("chartType");
            Node classNode = nodes.item(0).getFirstChild();
            String chartType = classNode.getNodeValue().trim();
            return chartType;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }
}